package com.xiao.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiao.entity.ChongEntity;
import com.xiao.entity.MemberEntity;
import com.xiao.entity.UserEntity;
import com.xiao.service.ChongService;
import com.xiao.service.MemberService;
import com.xiao.util.XiaoUtils;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("chong")
public class ChongController {

	@Autowired
	private ChongService chongService;

	@Autowired
	private MemberService memberService;

	@RequestMapping("toChong")
	public String toChong() {
		return "chong/chong";
	}

	@RequestMapping("findAll")
	@ResponseBody
	public JSONObject findAll(ChongEntity chongEntity) {
		List<ChongEntity> findAll = chongService.findAllByPager(chongEntity);
		int count = chongService.findAllCount();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", findAll);
		jsonObject.put("total", count);
		return jsonObject;
	}

	@RequestMapping("toInsert")
	public String toInsert() {
		return "chong/insert";
	}

	@RequestMapping("insert")
	@ResponseBody
	public int insert(ChongEntity chongEntity,HttpServletRequest request) {
		HttpSession session = request.getSession();
		UserEntity attribute = (UserEntity)session.getAttribute("USER");
		int uid = attribute.getUid();
		chongEntity.setUid(uid);
		String currentTime = XiaoUtils.getCurrentTimeMes();
		chongEntity.setOtime(currentTime);

		chongService.insert(chongEntity);
		//获取这个rid
		int rid = chongEntity.getRid();
		//找到这个member
		MemberEntity mem = memberService.findOneByRid(rid);
		//获取mem中的金额
		Double rmoney = mem.getRmoney();
		//计算总金额
		rmoney += chongEntity.getOlastmoney();
		//放入
		mem.setRmoney(rmoney);
		//更新数据
		memberService.update(mem);
		return 1;

	}

	@RequestMapping("toUpdate")
	public String toUpdate(int oid, Model model) {
		ChongEntity chongEntity = chongService.findOneByOid(oid);
		model.addAttribute("ar", chongEntity);
		return "chong/update";
	}

	@RequestMapping("update")
	@ResponseBody
	public int update(ChongEntity chongEntity) {
		chongService.update(chongEntity);
		return 1;
	}

	@RequestMapping("findAllNoPager")
	@ResponseBody
	public List<ChongEntity> findAllNoPager(){
		return chongService.findAll();
	}

}
